﻿using System;
using System.Windows.Documents;

using agsXMPP;

using VSTalk.Engine.Core.Context;
using VSTalk.Engine.Core.Feed;
using VSTalk.Model;

namespace VSTalk.Engine.ViewModel.Messenger.ThreadRenderer.BlockBuilder
{
    public class SubjectBlockBuilder
    {
        private Client _client;

        public SubjectBlockBuilder(Client client)
        {
            _client = client;
        }

        public IModelContext ModelContext
        {
            get { return AppServices.Get<IModelContext>(); }
        }

        public Block CreateBlock(IMessage message)
        {
            var header = CreateHeader(message);
            var body = CreateSubject(message);
            var block = Join(header, body);
            return block;
        }

        private Inline CreateSubject(IMessage message)
        {
            var subj = message.XmppMessage.Subject;
            var span = new Span();
            span.Inlines.Add(subj);
            return new Italic(new Bold(span));
        }

        private Inline CreateHeader(IMessage message)
        {
            var from = message.XmppMessage.From;
            var date = message.Date;
            var name = GetName(from);
            var span = new Span();
            var format = date >= DateTime.Today
                ? string.Format("{0} {1:t}", name, date)
                : string.Format("{0} {1:g}", name, date);
            span.Inlines.Add(format);
            return new Bold(span);
        }

        private string GetName(Jid @from)
        {
            if (@from == null) return _client.Login;
            var client = ModelContext.GetClientByJid(from);
            if (client != null)
            {
                return client.Login;
            }
            var interlocutor = ModelContext.GetContactByJid(_client.Id, @from);
            if (interlocutor != null)
            {
                return interlocutor.Name;
            }
            var room = ModelContext.GetRoomByJid(_client.Id, @from);
            if (room != null)
            {
                return @from.Resource ?? room.Name;
            }
            return from;
        }

        private Block Join(Inline header, Inline body)
        {
            var paragraph = new Paragraph();
            paragraph.Inlines.Add(header);
            paragraph.Inlines.Add(": ");
            paragraph.Inlines.Add(body);
            return paragraph;
        }
    }
}